﻿Imports System.Data.SqlClient
Imports RunEnv
Imports Tool
Imports System.Windows.Forms
Imports System.Drawing
Imports System.IO

Public Class dlgItem
    Private Const COL_Key As Integer = 0
    Private Const COL_Value As Integer = 1

    Private marrIDValues As Object()

    Private mblnEditState As Boolean
    Private mblnIsAddNewMode As Boolean

    Private mobjCPrimeEditor As CPrimeEditor
    Private mobjCTableInfo As CTableInfo
    Private mobjPageMove As IPageMove


    Private mdbTableValue As DataTable
    Private mdataAdapter As SqlDataAdapter

    Private mblnCancelSave As Boolean

    Public Property EditState() As Boolean
        Get
            Return mblnEditState
        End Get
        Set(value As Boolean)
            mblnEditState = value
            SetEditState(mblnEditState)
        End Set
    End Property

    Private Sub SetEditState(ByVal isEditState As Boolean)
        Dim field As CField
        SetToolBarState(isEditState)
        If Not isEditState Then
            DataGridView1.Columns(COL_Value).ReadOnly = True
            mblnIsAddNewMode = False
            Exit Sub
        End If

        For row As Integer = 0 To mobjCTableInfo.Fields.Count - 1
            field = mobjCTableInfo.Fields(row + 1)
            If Not field.IsReadOnly Then
                DataGridView1.Item(COL_Value, row).ReadOnly = False
            End If
        Next

    End Sub

    Private Sub SetToolBarState(ByVal isEditState As Boolean)
        Me.ToolStripButtonAdd.Enabled = Not isEditState
        Me.ToolStripButtonEdit.Enabled = Not isEditState
        Me.ToolStripButtonCancel.Enabled = isEditState
        Me.ToolStripButtonSave.Enabled = isEditState
        Me.ToolStripButtonFirst.Enabled = Not isEditState
        Me.ToolStripButtonLast.Enabled = Not isEditState
        Me.ToolStripButtonNext.Enabled = Not isEditState
        Me.ToolStripButtonPrevious.Enabled = Not isEditState
    End Sub

    Private Sub SetToolBarPageMoveState(ByVal isShowPageMove As Boolean)
        Me.ToolStripSeparator1.Visible = isShowPageMove
        Me.ToolStripButtonFirst.Visible = isShowPageMove
        Me.ToolStripButtonPrevious.Visible = isShowPageMove
        Me.ToolStripButtonNext.Visible = isShowPageMove
        Me.ToolStripButtonLast.Visible = isShowPageMove
    End Sub

    Public Sub Init(ByVal primeEditor As CPrimeEditor, Optional ByVal pageMove As IPageMove = Nothing)
        mobjCPrimeEditor = primeEditor
        mobjCTableInfo = primeEditor.TableInfo
        mobjCTableInfo.SetDlgItem(Me)
        mobjPageMove = pageMove
        If IsNothing(pageMove) Then
            SetToolBarPageMoveState(False)
        End If
        Me.Text = mobjCTableInfo.ManagerTitle
    End Sub

    Public Function ShowOpen(ByVal isAddNewMode As Boolean,
                             ByVal isEditState As Boolean,
                             Optional ByVal IDValues As Object() = Nothing) As Boolean
        Try
            InitTableUI()
            InitDB()
            mblnIsAddNewMode = isAddNewMode
            If IsArray(IDValues) Then
                marrIDValues = IDValues
            Else
                mblnIsAddNewMode = True
            End If
            If mblnIsAddNewMode Then
                ReDim marrIDValues(mobjCTableInfo.IDFields.Count)
                EditState = True
            Else
                EditState = isEditState
            End If
            If Not RefreshTable() Then
                Return False
            End If
            Me.ShowDialog()
            Return True
        Catch ex As Exception
            MsgBox("卡片显示失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
            Return False
        End Try
    End Function

    Public Function RefreshTable() As Boolean
        mdbTableValue = New DataTable
        Try
            For i As Integer = LBound(mobjCTableInfo.IDFields) To UBound(mobjCTableInfo.IDFields)
                If mblnIsAddNewMode Then
                    mdataAdapter.SelectCommand.Parameters("@" & mobjCTableInfo.IDFields(i)).Value = DBNull.Value
                Else
                    mdataAdapter.SelectCommand.Parameters("@" & mobjCTableInfo.IDFields(i)).Value = marrIDValues(i)
                End If
            Next
            mdataAdapter.Fill(mdbTableValue)
            If mblnIsAddNewMode Then
                mdbTableValue.Rows.Add(mdbTableValue.NewRow)
                SetDefaultValue()
            End If
            If mdbTableValue.Rows.Count <> 1 Then
                MsgBox("键无效，刷新失败！", MsgBoxStyle.Exclamation, "系统提示")
                Me.Close()
                Return False
            End If
            DataGridView1.Refresh()
            PictureBox1.Image = Nothing
            Return True
        Catch ex As Exception
            MsgBox("数据刷新失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
            Return False
        End Try
    End Function

    Public Sub SetDefaultValue()
        Dim field As CField
        Try
            For i As Integer = 1 To mobjCTableInfo.Fields.Count
                field = CType(mobjCTableInfo.Fields(i), CField)
                If Len(field.DefaultValue) <= 0 AndAlso field.DataType = "bit" Then
                    mdbTableValue.Rows(0).Item(i - 1) = False
                End If
                If Len(field.DefaultValue) <= 0 Then Continue For
                If Not IsDBNull(CType(mobjCTableInfo.Fields(i), CField).GetDefaultValue()) AndAlso Len(CType(mobjCTableInfo.Fields(i), CField).GetDefaultValue()) > 0 Then
                    mdbTableValue.Rows(0).Item(i - 1) = CType(mobjCTableInfo.Fields(i), CField).GetDefaultValue()
                End If
            Next
        Catch ex As Exception
            MsgBox("设置默认值出错," & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try
    End Sub

    Public Sub SetValue(ByVal fieldName As String, ByVal value As Object)
        mdbTableValue.Rows(0).Item(fieldName) = value
        DataGridView1.Refresh()
    End Sub

    Public Function GetValue(ByVal fieldName As String) As Object
        Return mdbTableValue.Rows(0).Item(fieldName)
    End Function

    Private Sub InitTableUI()
        Dim field As CField
        With DataGridView1
            .VirtualMode = True
            .AllowUserToAddRows = False
            .RowCount = mobjCTableInfo.Fields.Count
            .ColumnCount = 2
            .Columns(COL_Key).HeaderText = "属性"
            .Columns(COL_Value).HeaderText = "值"
            .Columns(COL_Key).ReadOnly = True
            .Columns(COL_Value).Width = 150
            .Columns(COL_Value).DefaultCellStyle.Alignment = Windows.Forms.DataGridViewContentAlignment.MiddleCenter
            For row As Integer = 0 To .RowCount - 1
                .Item(COL_Key, row).Style.BackColor = Drawing.Color.Aqua
                field = mobjCTableInfo.Fields(row + 1)

                'If field.DataType <> "image" Then
                .Item(COL_Value, row).ValueType = CDBConnection.SqlType2Type(field.DataType)
                'End If

                If .Item(COL_Value, row).ValueType = GetType(Boolean) Then
                    .Item(COL_Value, row) = New DataGridViewCheckBoxCell
                End If

                If .Item(COL_Value, row).ValueType = GetType(DateTime) Then
                    .Item(COL_Value, row) = New CalendarCell
                End If


                .Rows(row).Visible = field.IsVisible

                If field.IsReadOnly Then
                    .Item(COL_Value, row).Style.BackColor = Drawing.Color.LightBlue
                    .Item(COL_Value, row).ReadOnly = True
                Else
                    If field.FieldMode = CField.FieldRelation.RelationTranslate Then
                        .Item(COL_Value, row).Style.BackColor = Drawing.Color.LightBlue
                        .Item(COL_Value, row).ReadOnly = True
                        field.IsReadOnly = True
                    End If
                End If

                If Not field.IsCanBeNull Then
                    .Rows(row).HeaderCell.Value = "*"
                End If
            Next
        End With
    End Sub

    Private Sub InitDB()
        mdataAdapter = New SqlDataAdapter
        mdataAdapter.SelectCommand = mobjCTableInfo.GetSelectCommand()
        mdataAdapter.UpdateCommand = mobjCTableInfo.GetUpdateCommand()
        mdataAdapter.InsertCommand = mobjCTableInfo.GetInsertCommand()
    End Sub

    Private Sub DataGridView1_CellDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
        Dim field As CField
        Dim dlg1 As New dlgGetValue
        Dim value As Object
        If Not EditState Then Exit Sub
        field = CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField)
        If field.DataType = "image" Then
            Me.ContextMenuStrip1.Show(Control.MousePosition)
            Exit Sub
        End If
        If field.FieldMode = CField.FieldRelation.RelationTranslate Then
            value = dlg1.ShowOpen(field)
            If value Is Nothing Then Exit Sub
            mobjCTableInfo.SetValue(field.FieldName, value)
            field.notifyObservers(value, field)
        End If
    End Sub

    Private Sub DataGridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        Try
            If Not EditState Then Exit Sub
            If e.ColumnIndex <> COL_Value Then Exit Sub
            If IsDBNull(e.Value) Then Exit Sub
            If Len(e.Value) = 0 Then Exit Sub
            If CDBConnection.SqlType2Type(CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).DataType) = (New Double()).GetType Then
                mdbTableValue.Rows(0).Item(e.RowIndex) = String.Format("{0:f" & CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).NumericScale & "}", Double.Parse(e.Value))
                'e.Value = mdbTableValue.Rows(0).Item(e.RowIndex)
            End If
        Catch ex As Exception
            MsgBox("单元格格式化失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try
    End Sub

    Private Sub DataGridView1_CellValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
        Try
            If Not EditState Then Exit Sub
            If e.ColumnIndex <> COL_Value Then Exit Sub
            If IsDBNull(e.FormattedValue) Then Exit Sub
            If Len(e.FormattedValue) = 0 Then Exit Sub
            If CDBConnection.SqlType2Type(CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).DataType) = (New Integer()).GetType Then
                Integer.Parse(e.FormattedValue)
            ElseIf CDBConnection.SqlType2Type(CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).DataType) = (New Double()).GetType Then
                String.Format("{0:f" & CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).NumericScale & "}", Double.Parse(e.FormattedValue))
                'DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value
                'mdbTableValue.Rows(0).Item(e.RowIndex) 
            End If
            e.Cancel = False
            DataGridView1.Refresh()
        Catch ex As Exception
            MsgBox("数值格式化失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
            e.Cancel = True
            mblnCancelSave = True
        End Try
    End Sub

    '表格数据与dataTable的同步
    ' ********************************************************************************
    Private Sub DataGridView1_CellValueNeeded(sender As Object, e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValueNeeded
        Dim photo As Byte()
        Try
            If e.ColumnIndex = COL_Key Then
                e.Value = CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).FieldTitle
            Else
                If CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).DataType = "image" Then
                    If IsDBNull(mdbTableValue.Rows(0).Item(e.RowIndex)) Then
                        Exit Sub
                    End If
                    photo = mdbTableValue.Rows(0).Item(e.RowIndex)
                    Dim stream As MemoryStream = New MemoryStream(photo)
                    Me.PictureBox1.Image = Image.FromStream(stream)
                    Exit Sub
                End If
                e.Value = mdbTableValue.Rows(0).Item(e.RowIndex)
            End If
        Catch ex As Exception
            MsgBox("刷新界面数据失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try

    End Sub

    Private Sub DataGridView1_CellValuePushed(sender As Object, e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValuePushed
        Try
            If e.ColumnIndex = COL_Value Then
                mdbTableValue.Rows(0).Item(e.RowIndex) = e.Value
            End If

            If Not mobjCTableInfo Is Nothing Then
                CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField).notifyObservers(DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value,
                                CType(mobjCTableInfo.Fields(e.RowIndex + 1), CField))
            End If
        Catch ex As Exception
            MsgBox("保存界面数据失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try

    End Sub

    Private Sub ToolStripButtonAdd_Click(sender As Object, e As System.EventArgs) Handles ToolStripButtonAdd.Click
        mblnIsAddNewMode = True
        EditState = True
        RefreshTable()
    End Sub

    Private Sub ToolStripButtonEdit_Click(sender As Object, e As System.EventArgs) Handles ToolStripButtonEdit.Click
        EditState = True
    End Sub

    Private Sub ToolStripButtonCancel_Click(sender As Object, e As System.EventArgs) Handles ToolStripButtonCancel.Click
        If marrIDValues(0) Is Nothing Then
            Me.Close()
            Exit Sub
        End If
        mblnIsAddNewMode = False
        'DataGridView1.CurrentCell = Nothing
        If Not IsArray(marrIDValues) Then
            Me.Close()
        Else
            DataGridView1.CancelEdit()
            mdbTableValue.RejectChanges()
            RefreshTable()
            DataGridView1.Refresh()
            EditState = False
        End If
    End Sub

    Private Sub ToolStripButtonSave_Click(sender As Object, e As System.EventArgs) Handles ToolStripButtonSave.Click
        Try
            If mblnIsAddNewMode And mobjCTableInfo.IsAutoID Then
                SetAutoID()
            End If
            mblnCancelSave = False
            Me.Validate()
            If mblnCancelSave = True Then
                Exit Sub
            End If
            DataGridView1.CurrentCell = Nothing
            If Not CheckBeforeSave() Then
                Exit Sub
            End If
            mdataAdapter.Update(mdbTableValue)

            For i As Integer = LBound(mobjCTableInfo.IDFields) To UBound(mobjCTableInfo.IDFields)
                marrIDValues(i) = mdbTableValue.Rows(0).Item(mobjCTableInfo.IDFields(i))
            Next

            EditState = False
        Catch ex As Exception
            MsgBox("保存失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try

    End Sub

    'Private Function CheckCurrentCell(ByVal rowIndex As Integer, ByVal formattedValue As Object) As Boolean
    '    Try
    '        If CDBConnection.SqlType2Type(CType(mobjCTableInfo.Fields(rowIndex + 1), CField).DataType) = (New Integer()).GetType Then
    '            Integer.Parse(formattedValue)
    '        ElseIf CDBConnection.SqlType2Type(CType(mobjCTableInfo.Fields(rowIndex + 1), CField).DataType) = (New Double()).GetType Then
    '            DataGridView1.Rows(rowIndex).Cells(COL_Value).Value = String.Format("{0:f" & CType(mobjCTableInfo.Fields(rowIndex + 1), CField).NumericScale & "}", Double.Parse(formattedValue))
    '        End If
    '        Return True
    '    Catch ex As Exception
    '        MsgBox("数值格式化失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
    '        Return False
    '    End Try
    'End Function

    Private Sub SetAutoID()
        Dim maxID As String = ""
        Dim obj As New CToolBill
        maxID = obj.GetNewMaxBillNo(mobjCTableInfo.ManagerTitle)
        SetValue(mobjCTableInfo.IDFields(0), maxID)
    End Sub

    Private Function CheckBeforeSave() As Boolean
        Try
            Dim sqlWhere As String = ""
            Dim sql As String
            For i As Integer = 0 To mobjCTableInfo.Fields.Count - 1
                If Not CType(mobjCTableInfo.Fields(i + 1), CField).IsCanBeNull Then
                    If IsDBNull(mdbTableValue.Rows(0).Item(i)) Then
                        MsgBox(CType(mobjCTableInfo.Fields(i + 1), CField).FieldTitle & "不能为空!", MsgBoxStyle.Exclamation, "系统提示")
                        Return False
                    ElseIf Len(mdbTableValue.Rows(0).Item(i)) = 0 Then
                        MsgBox(CType(mobjCTableInfo.Fields(i + 1), CField).FieldTitle & "不能为空!", MsgBoxStyle.Exclamation, "系统提示")
                        Return False
                    End If
                End If
            Next

            Dim fieldCount As Integer
            Dim str1 As String = ""
            If Not mblnIsAddNewMode Then
                For i As Integer = 0 To mobjCTableInfo.IDFields.Count - 1
                    If Len(str1) = 0 Then
                        str1 = mobjCTableInfo.IDFields(i) & " <>'" & mdbTableValue.Rows(0).Item(mobjCTableInfo.IDFields(i), DataRowVersion.Original) & "'"
                    Else
                        str1 = str1 & " And " & mobjCTableInfo.IDFields(i) & " <>'" & mdbTableValue.Rows(0).Item(mobjCTableInfo.IDFields(i), DataRowVersion.Original) & "'"
                    End If
                Next
            End If
            If Len(str1) > 0 Then
                str1 = " And " & str1
            End If

            For i As Integer = 0 To mobjCTableInfo.Fields.Count - 1
                If CType(mobjCTableInfo.Fields(i + 1), CField).IsUnique Then
                    sqlWhere = " Where " & CType(mobjCTableInfo.Fields(i + 1), CField).FieldName & "='" & mdbTableValue.Rows(0).Item(i) & "'"
                    sql = "Select Count(*)" _
                        & " From " & mobjCTableInfo.TableName _
                        & sqlWhere _
                        & str1

                    fieldCount = gcnnDBMain.GetIntCalculateValue(sql)
                    If fieldCount <> 0 Then
                        MsgBox(CType(mobjCTableInfo.Fields(i + 1), CField).FieldTitle & "要求值唯一!", MsgBoxStyle.Exclamation, "系统提示")
                        Return False
                    End If
                End If
            Next

            Return True
        Catch ex As Exception
            MsgBox("数据保存前检查失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
            Return False
        End Try
    End Function

    Private Sub ToolStripMenuItemDeleteImage_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItemDeleteImage.Click
        Dim field As CField
        For i As Integer = 1 To mobjCTableInfo.Fields.Count
            field = mobjCTableInfo.Fields(i)
            If field.DataType = "image" Then
                mdbTableValue.Rows(0).Item(i - 1) = DBNull.Value
                PictureBox1.Image = Nothing
            End If
        Next
    End Sub

    Private Sub ToolStripMenuItemAddImage_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItemAddImage.Click
        Dim field As CField
        Dim imgFileName As String
        Dim img As Image
        Dim stream As MemoryStream = New MemoryStream
        For i As Integer = 0 To mobjCTableInfo.Fields.Count - 1
            field = mobjCTableInfo.Fields(i + 1)
            If field.DataType = "image" Then
                imgFileName = GetImageFileName()
                If Len(imgFileName) > 0 Then
                    img = Image.FromFile(imgFileName)
                    img.Save(stream, img.RawFormat)
                    stream.Position = 0

                    Dim reader As BinaryReader = New BinaryReader(stream)
                    Dim photo() As Byte = reader.ReadBytes(Int(stream.Length))
                    If photo.Length > 1024 * 1024 Then
                        MsgBox("图片大于1M，无法保存！", MsgBoxStyle.Exclamation, "系统提示")
                        Exit Sub
                    End If
                    mdbTableValue.Rows(0).Item(i) = photo
                    PictureBox1.Image = img
                    reader.Close()
                    stream.Close()
                    Exit For
                End If
            End If
        Next
    End Sub

    Private Function GetImageFileName() As String
        Dim openFileDialog1 As New OpenFileDialog

        openFileDialog1.Filter = "所有图像文件|*.bmp;*.jpg;*.gif;|位图（*.bmp;*.jpg;）|*.bmp;*.jpg;"
        If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Return openFileDialog1.FileName
        End If
        Return ""
    End Function

    Private Sub ToolStripButtonPrevious_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButtonPrevious.Click
        mobjPageMove.MovePage(IPageMove.MoveDirection.MovePrevious, marrIDValues)
        RefreshTable()
    End Sub

    Private Sub ToolStripButtonNext_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButtonNext.Click
        mobjPageMove.MovePage(IPageMove.MoveDirection.MoveNext, marrIDValues)
        RefreshTable()
    End Sub

    Private Sub ToolStripButtonFirst_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButtonFirst.Click
        mobjPageMove.MovePage(IPageMove.MoveDirection.MoveFirst, marrIDValues)
        RefreshTable()
    End Sub

    Private Sub ToolStripButtonLast_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButtonLast.Click
        mobjPageMove.MovePage(IPageMove.MoveDirection.MoveLast, marrIDValues)
        RefreshTable()
    End Sub
End Class